using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.IsolatedStorage;
using System.Xml;
using System.IO;
using System.Xml.Serialization;

namespace Sudoku.Utilities
{
	public class FileIOService
	{
		IsolatedStorageFile store = null;
		
		public FileIOService()
		{
#if WINDOWS_PHONE
			store = IsolatedStorageFile.GetUserStoreForApplication();
#endif
		}

		public void SaveFile(String s_FileName, object o_ToSave, Type t_Type)
		{
#if WINDOWS_PHONE
			IsolatedStorageFileStream stream = store.OpenFile(s_FileName, FileMode.Create, FileAccess.ReadWrite);
#else
			FileStream stream = File.Open(s_FileName, FileMode.Create);			
#endif

			XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
			ns.Add("", "");
			XmlSerializer serializer = new XmlSerializer(t_Type);
			serializer.Serialize(stream, o_ToSave);

			stream.Close();
		}

		public object LoadFile(String s_FileName, Type t_Type)
		{
			if (!IsFileAvaible(s_FileName))
			{
				// should not be here
				throw new Exception("Requested File " + s_FileName  + " not found!");
			}

#if WINDOWS_PHONE
			IsolatedStorageFileStream stream = store.OpenFile(s_FileName, FileMode.Open, FileAccess.Read);
#else
			FileStream stream = File.Open(s_FileName, FileMode.Open);
#endif

			XmlSerializer serializer = new XmlSerializer(t_Type);
			object o_Loaded = serializer.Deserialize(stream);

			stream.Close();

			return o_Loaded;
		}

		public bool IsFileAvaible(String s_FileName)
		{
#if WINDOWS_PHONE
			return store.FileExists(s_FileName);
#else
			return File.Exists(s_FileName);
#endif
		}

		public void ClearFile(String s_FileName)
		{
#if WINDOWS_PHONE
			if (IsFileAvaible(s_FileName))
			{
				store.DeleteFile(s_FileName);
			}
#else
			File.Delete(s_FileName);	
#endif
		}


	}
}
